package com.nhc.view;

import android.app.Activity;
import android.content.Context;
import android.graphics.Point;
import android.os.Environment;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.astrob.TileSource.BaiDRMapsTileSource;
import com.astrob.TileSource.GoogleMapsTileSource;
import com.astrob.TileSource.OCMDGXMapsTileSource;
import com.astrob.activitys.OSMActivity;
import com.astrob.model.LonLat;
import com.astrob.naviframe.Start;
import com.astrob.nhcmap.R;
import com.astrob.util.SomeDataMapManger;
import com.astrob.util.SysUtils;
import com.astrob.util.Utils;
import com.astrob.view.MapViewS;
import com.nhc.model.MapSetInfo;

import org.mapsforge.core.model.LatLong;
import org.mapsforge.core.model.MapPosition;
import org.mapsforge.core.util.Parameters;
import org.mapsforge.map.android.graphics.AndroidGraphicFactory;
import org.mapsforge.map.android.input.TouchGestureHandler;
import org.mapsforge.map.android.rotation.RotateView;
import org.mapsforge.map.android.util.AndroidPreferences;
import org.mapsforge.map.android.util.AndroidUtil;
import org.mapsforge.map.datastore.MapDataStore;
import org.mapsforge.map.datastore.MultiMapDataStore;
import org.mapsforge.map.layer.cache.TileCache;
import org.mapsforge.map.layer.hills.HillsRenderConfig;
import org.mapsforge.map.layer.hills.MemoryCachingHgtReaderTileSource;
import org.mapsforge.map.layer.hills.SimpleShadingAlgorithm;
import org.mapsforge.map.layer.renderer.TileRendererLayer;
import org.mapsforge.map.model.common.PreferencesFacade;
import org.mapsforge.map.reader.MapFile;
import org.mapsforge.map.rendertheme.InternalRenderTheme;
import org.mapsforge.map.rendertheme.XmlRenderTheme;
import org.mapsforge.map.scalebar.MapScaleBar;
import org.osmdroid.api.IGeoPoint;
import org.osmdroid.events.MapListener;
import org.osmdroid.tileprovider.MapTileProviderBasic;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
import org.osmdroid.views.Projection;
import org.osmdroid.views.overlay.ScaleBarOverlay;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import zuo.biao.library.model.Entry;

public class MultiMapView extends FrameLayout {

    public MultiMapView(Context context) {
        super(context);
        init();
    }

    public MultiMapView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public MapViewS mMapViewS;
    public MapView mMapViewOnline;

    private void init() {
        LayoutInflater inflate = (LayoutInflater) getContext()
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflate.inflate(R.layout.multimap_view, this, true);

        mMapViewS = (MapViewS) this.findViewById(R.id.id_mapview);
        initOSM();
        intMapsforge();
    }

    private int _mapsource = 1000;//
    //1000-smf(火星坐标) 1001-mapsforge（GPS） 渲染的地形图
    //0,1,3--google(火星坐标) 2-OSM（GPS）

    public boolean isgcj02 = true; //是火星坐标

    public void setMapsource(int mapsource) {
        _mapsource = mapsource;
        isgcj02 = true;
        mMapViewS.setVisibility(View.GONE);
        mapView.setVisibility(View.GONE);
        mMapViewOnline.setVisibility(View.GONE);
        AndroidGraphicFactory.clearResourceMemoryCache();
        if (_mapsource == 1000) {
            mMapViewS.setVisibility(View.VISIBLE);
        } else if (_mapsource == 1001) {
            isgcj02 = false;
            mapView.setVisibility(View.VISIBLE);
        } else {
            mMapViewOnline.setVisibility(View.VISIBLE);
            if (_mapsource == 2 || _mapsource >= 1002) {
                isgcj02 = false; //加载的gemf是非火星坐标
            }
        }

//        isgcj02 = true; //保存的osm.db是火星坐标


        onChangeMapViewOnlineMapsource();
    }

    public int getMapsource() {
        return _mapsource;
    }

    public String getMapsourceStr(int mapsource) {
        String strMapsource = "";
        switch (mapsource) {
            default:
                break;
            case 0:
                //Google-Sat
            {
                strMapsource = "谷歌\n卫星";
            }
            break;
            case 1:
                //GoogleNormal
            {
                strMapsource = "谷歌";
            }
            break;
            case 2:
                //OSMWinter DEM
            {
                strMapsource = "OSM\n等高线";
            }
            break;
            case 3:
                //Google DEM
            {
                strMapsource = "高德\n地图";

            }
            break;
            case 1000:
            {
                strMapsource = "中国地图";

            }
            break;
            case 1001:
            {
                strMapsource = "离线\n等高线";

            }
            break;
            case 1002:
            {
                strMapsource = "离线\n栅格图";

            }
            break;
        }
        return strMapsource;
    }

    public void onChangeMapViewOnlineMapsource() {
        SomeDataMapManger.detach();
        MapTileProviderBasic provider = new MapTileProviderBasic(getContext());
        mMapViewOnline.setTileProvider(provider);

        intMapsforge();//切换数据源后，会不会死机？;这里有问题，会导致地图layer错乱， 如果一定要切换则图层必需重新加入
        mMapViewOnline.setMaxZoomLevel(20);
        switch (_mapsource) {
            default:
                break;
            case 1002://gemf -- or 所有离线格式
                isgcj02 = MapSetInfo.getInstance().isgcj02();
                mMapViewOnline.setMaxZoomLevel(18);
                SomeDataMapManger.initmapViewData3(mMapViewOnline, getContext(), SysUtils.getInstance().mapfilepath2);
                mMapViewOnline.setUseDataConnection(true);
                break;
            case 1003://mbtiles
                isgcj02 = MapSetInfo.getInstance().isgcj02();
                mMapViewOnline.setMaxZoomLevel(18);
                SomeDataMapManger.initmapViewData3(mMapViewOnline, getContext(), SysUtils.getInstance().mapfilepath3);
                mMapViewOnline.setUseDataConnection(true);
                break;
            case 1004://zip
                isgcj02 = MapSetInfo.getInstance().isgcj02();
                mMapViewOnline.setMaxZoomLevel(18);
                SomeDataMapManger.initmapViewData3(mMapViewOnline, getContext(), SysUtils.getInstance().mapfilepath4);
                mMapViewOnline.setUseDataConnection(true);
                break;
            case 0:
                //Google-Sat
            {
                String str1 = "http://mt0.google.cn/vt/lyrs=s&hl=zh-CN&gl=cn&scale=2";
                String str2 = "http://mt1.google.cn/vt/lyrs=s&hl=zh-CN&gl=cn&scale=2";
                String str3 = "http://mt2.google.cn/vt/lyrs=s&hl=zh-CN&gl=cn&scale=2";
                String str4 = "http://mt3.google.cn/vt/lyrs=s&hl=zh-CN&gl=cn&scale=2";
                GoogleMapsTileSource googleMapsSatTileSource = new GoogleMapsTileSource("Google-Sat", 3, 19, 256,
                        ".png", new String[]{str1, str2, str3, str4});
                mMapViewOnline.setTileSource(googleMapsSatTileSource);
//                tv_tile.setText("谷歌\n卫星");
            }
            break;
            case 1:
                //GoogleNormal
            {
                String str1 = "http://mt0.google.cn/vt/lyrs=m&hl=zh-CN&gl=cn&scale=2";
                String str2 = "http://mt1.google.cn/vt/lyrs=m&hl=zh-CN&gl=cn&scale=2";
                String str3 = "http://mt2.google.cn/vt/lyrs=m&hl=zh-CN&gl=cn&scale=2";
                String str4 = "http://mt3.google.cn/vt/lyrs=m&hl=zh-CN&gl=cn&scale=2";
                GoogleMapsTileSource googleMapsTileSource = new GoogleMapsTileSource("GoogleNormal", 2, 19, 256,
                        ".png", new String[]{str1, str2, str3, str4});
                mMapViewOnline.setTileSource(googleMapsTileSource);
//                tv_tile.setText("谷歌");
            }
            break;
            case 23: {
                //天地图  --
                String str1 = "http://t0.tianditu.cn/DataServer?T=cia_w";
                String str2 = "http://t1.tianditu.cn/DataServer?T=cia_w";
                String str3 = "http://t2.tianditu.cn/DataServer?T=cia_w";
                String str4 = "http://t3.tianditu.cn/DataServer?T=cia_w";
                String str5 = "http://t4.tianditu.cn/DataServer?T=cia_w";
                GoogleMapsTileSource googleMapsSatTileSource = new GoogleMapsTileSource("tianditu", 3, 19, 256,
                        ".png", new String[]{str1, str2, str3, str4});

                mMapViewOnline.setTileSource(googleMapsSatTileSource);
            }
            break;
            case 3: {
                //高德地图
                String str1 = "http://wprd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7";
                String str2 = "http://wprd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7";
                String str3 = "http://wprd03.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7";
                String str4 = "http://wprd04.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7";
                GoogleMapsTileSource googleMapsSatTileSource = new GoogleMapsTileSource("Gaode", 3, 19, 256,
                        ".png", new String[]{str1, str2, str3, str4});

                mMapViewOnline.setTileSource(googleMapsSatTileSource);
            }
            break;
            case 2:
                //OSMWinter DEM
            {
                String str1 = "http://s0.outdooractive.com/osm/OSMWinter/";
                String str2 = "http://s1.outdooractive.com/osm/OSMWinter/";
                String str3 = "http://s2.outdooractive.com/osm/OSMWinter/";
                String str4 = "http://s3.outdooractive.com/osm/OSMWinter/";
                OCMDGXMapsTileSource oCMDGXMapsTileSource = new OCMDGXMapsTileSource("OSMWinter-DGX", 3, 18, 256,
                        ".png", new String[]{str1, str2, str3, str4});
                mMapViewOnline.setTileSource(oCMDGXMapsTileSource);
//                tv_tile.setText("OSM\n等高线");
            }
            break;
            case 22:
                //百度地图
            {


//            http://online0.map.bdimg.com/onlinelabel/?qt=tile&x=707&y=217&z=12&styles=pl&udt=20151021&scaler=1&p=1
                String str1 = "http://online0.map.bdimg.com/onlinelabel/?qt=tile&styles=pl&udt=20151021&scaler=1&p=1";
                String str2 = "http://online1.map.bdimg.com/onlinelabel/?qt=tile&styles=pl&udt=20151021&scaler=1&p=1";
                String str3 = "http://online2.map.bdimg.com/onlinelabel/?qt=tile&styles=pl&udt=20151021&scaler=1&p=1";
                String str4 = "http://online3.map.bdimg.com/onlinelabel/?qt=tile&styles=pl&udt=20151021&scaler=1&p=1";
                String str5 = "http://online4.map.bdimg.com/onlinelabel/?qt=tile&styles=pl&udt=20151021&scaler=1&p=1";
                BaiDRMapsTileSource baiDRMapsTileSource = new BaiDRMapsTileSource("Baidu", 3, 18, 256,
                        ".png", new String[]{str1, str2, str3, str4, str5});
                mMapViewOnline.setTileSource(baiDRMapsTileSource);
            }
            break;
            case 31:
                //Google DEM
            {
                String str1 = "http://mt0.google.cn/vt/lyrs=t@128&hl=zh-CN&gl=cn&src=app&s=Galileo";
                String str2 = "http://mt1.google.cn/vt/lyrs=t@128&hl=zh-CN&gl=cn&src=app&s=Galileo";
                String str3 = "http://mt2.google.cn/vt/lyrs=t@128&hl=zh-CN&gl=cn&src=app&s=Galileo";
                String str4 = "http://mt3.google.cn/vt/lyrs=t@128&hl=zh-CN&gl=cn&src=app&s=Galileo";
                GoogleMapsTileSource googleMapsSatTileSource = new GoogleMapsTileSource("Google-DGX", 3, 19, 256,
                        ".png", new String[]{str1, str2, str3, str4});
                mMapViewOnline.setTileSource(googleMapsSatTileSource);
//                tv_tile.setText("谷歌\n地形");
            }
            break;

        }

        updateMap();
    }
    
    // 对外接口
    public void updateMap() {
        if (_mapsource == 1000) {
            mMapViewS.updateMap();
        } else if (_mapsource == 1001) {
            mapView.getLayerManager().redrawLayers();
        } else {
            mMapViewOnline.invalidate();
        }
    }

    public void setScale(double scale) {
        try {
            if (_mapsource == 1000) {
                Start.getInstance().MapKit().setScale(scale);
            } else if (_mapsource == 1001) {
                if (scale <= 50000) {
                    mapView.getModel().mapViewPosition.setZoomLevel((byte) 14);
                } else {
                    mapView.getModel().mapViewPosition.setZoomLevel((byte) 16);
                }
            } else {
                if (scale <= 50000) {
                    mMapViewOnline.getController().setZoom(14);
                } else {
                    mMapViewOnline.getController().setZoom(16);
                }
            }
        } catch (Exception e) {

        }
    }

    public String getScaleString() {
        String strScale = "";
        if (SysUtils.getInstance().mapsource == 1000) {
            strScale = Start.getInstance().MapKit().getScaleString();
        } else if (SysUtils.getInstance().mapsource == 1001) {
            byte sale = mapView.getModel().mapViewPosition.getZoomLevel();
            switch (sale) {
                default:
                    break;
                case 0:
                    strScale = "6400km";
                    break;
                case 1:
                    strScale = "3200km";
                    break;
                case 2:
                    strScale = "1600km";
                    break;
                case 3:
                    strScale = "800km";
                    break;
                case 4:
                    strScale = "400km";
                    break;
                case 5:
                    strScale = "200km";
                    break;
                case 6:
                    strScale = "100km";
                    break;
                case 7:
                    strScale = "50km";
                    break;
                case 8:
                    strScale = "25km";
                    break;
                case 9:
                    strScale = "13km";
                    break;
                case 10:
                    strScale = "6km";
                    break;
                case 11:
                    strScale = "3.2km";
                    break;
                case 12:
                    strScale = "1.6km";
                    break;
                case 13:
                    strScale = "0.8km";
                    break;
                case 14:
                    strScale = "0.4km";
                    break;
                case 15:
                    strScale = "0.2km";
                    break;
                case 16:
                    strScale = "100m";
                    break;
                case 17:
                    strScale = "50m";
                    break;
                case 18:
                    strScale = "25m";
                    break;
                case 19:
                    strScale = "10m";
                    break;
                case 20:
                    strScale = "5m";
                    break;

            }


        }

        return strScale;
    }


    public Point LL2XY(LonLat ll) {
        Point B = new Point();
        if (_mapsource == 1000) {
            B = Start.getInstance().MapKit().LL2XY(ll);
            B.set((int) (B.x * mMapViewS._ws), (int) (B.y * mMapViewS._ws));
        } else if (_mapsource == 1001) {
            org.mapsforge.core.model.Point BB = mapView.getMapViewProjection().toPixels(new LatLong(ll.GetLat(), ll.GetLon()));
            B.set((int)BB.x, (int)BB.y);
        } else {
            Point mMapCoordsProjected = new Point();
            mMapViewOnline.getProjection().toProjectedPixels(ll.GetLat(),
                    ll.GetLon(), mMapCoordsProjected);
            Projection pj = mMapViewOnline.getProjection();
            pj.toPixelsFromProjected(mMapCoordsProjected, B);
        }

        return B;
    }

    public LonLat XY2LL(Point pt) {
        LonLat ll = new LonLat();
        if (_mapsource == 1000) {
            Point B = new Point();
            B.set((int) (pt.x / mMapViewS._ws), (int) (pt.y / mMapViewS._ws));
            ll = Start.getInstance().MapKit().XY2LL(pt);
        } else if (_mapsource == 1001) {
            LatLong geoPoint = mapView.getMapViewProjection().fromPixels(pt.x, pt.y);
            if (geoPoint != null) {
                ll = new LonLat(geoPoint.getLongitude(), geoPoint.getLatitude());
            }
        } else {
            IGeoPoint geoPoint = mMapViewOnline.getProjection().fromPixels(pt.x, pt.y);
            ll = new LonLat(geoPoint.getLongitude(), geoPoint.getLatitude());
        }
        return ll;
    }

    public void setMapOrientation(float degrees) {
        if (_mapsource == 1000) {
            Start.getInstance().MapKit().setRotation(degrees);
        } else if (_mapsource == 1001) {
            rotateViewMapsforge.setHeading(degrees);
            rotateViewMapsforge.postInvalidate();
        } else {
            mMapViewOnline.setMapOrientation(-degrees);
            mMapViewOnline.invalidate();
        }
    }

    //输入的是GPS原始坐标
    public void setMapCenter(LonLat ll) {
        if (ll == null) {
            return;
        }

        try {
            LonLat a2 = ll;
            if (isgcj02) {
                a2 = Utils.wgs84togcj02(ll.GetLon(), ll.GetLat());//Utils GPS to 火星坐标
            }

            if (_mapsource == 1000) {
                Start.getInstance().MapKit().setMapCenter(a2);//这里会异常；估计是其他页面崩溃后
            } else if (_mapsource == 1001) {
                mapView.setCenter(new LatLong(a2.GetLat(), a2.GetLon()));
            } else {
                _geopoint = new GeoPoint(a2.GetLat(), a2.GetLon());
                mMapViewOnline.getController().setCenter(_geopoint);
            }
        } catch (Exception e) {

        }

    }

    public LonLat getMapCenter() {
        LonLat ll = Start.getInstance().MapKit().getMapCenter();
        if (_mapsource == 1001) {
            MapPosition a = mapView.getModel().mapViewPosition.getMapPosition();
            ll.SetLonLat(a.latLong.longitude, a.latLong.latitude);
        } else if (_mapsource != 1000) {
            //瓦片图
            GeoPoint center = (GeoPoint) mMapViewOnline.getMapCenter();
            ll.SetLonLat(center.getLongitude(), center.getLatitude());
        }
        return ll;
    }

    public void zoomIn() {
        if (_mapsource == 1000) {
            Start.getInstance().MapKit().onZoomIn();
        } else if (_mapsource == 1001) {
            byte sale = mapView.getModel().mapViewPosition.getZoomLevel();
            if (sale >= 20) {
                return;
            }
            mapView.getModel().mapViewPosition.zoomIn();
        } else {
            int sale = mMapViewOnline.getZoomLevel(false);
            if (sale >= 20) {
                return;
            }
            mMapViewOnline.getController().zoomIn();
        }
    }

    public void zoomOut() {
        if (_mapsource == 1000) {
            Start.getInstance().MapKit().onZoomOut();
        } else if (_mapsource == 1001) {
            mapView.getModel().mapViewPosition.zoomOut();
        } else {
            mMapViewOnline.getController().zoomOut();
            mapView.setVisibility(View.GONE);
        }
    }

    public void moveMap(int dx, int dy) {
        if (_mapsource == 1000) {
            Start.getInstance().MapKit().moveMap(-dx, -dy);
        } else if (_mapsource == 1001) {
            mapView.getModel().mapViewPosition.moveCenter(-dx, -dy);
        } else {
            mMapViewOnline.getController().scrollBy(dx, dy);
        }
        updateMap();
    }

    //传入地图操作回调+地图显示图层
    public void setMapCallback(MapViewS.MapCallBack TMECallback, MapListener mapListener) {
        mMapViewS.mCallback = TMECallback;
        mMapViewOnline.setMapListener(mapListener);
        TouchGestureHandler touchGestureHandler = mapView.getTouchGestureHandler();
        touchGestureHandler.setMapListener(mapListener);
    }


    // OSM
    private ScaleBarOverlay mScaleBarOverlay;
    private MapController mMapController;
    private GeoPoint _geopoint = new GeoPoint(39.986250, 116.400025);//北京

    void initOSM() {
        mMapViewOnline = (MapView) this.findViewById(R.id.id_mapView_online);

        mMapViewOnline.setTilesScaledToDpi(true);

        //添加比例尺
        mScaleBarOverlay = new ScaleBarOverlay(mMapViewOnline);
        mMapViewOnline.getOverlays().add(mScaleBarOverlay);
        mScaleBarOverlay.setAlignBottom(true);//底部显示
        mScaleBarOverlay.setAlignRight(true);//底部显示
        mScaleBarOverlay.setLineWidth(1 * (getResources().getDisplayMetrics()).density);
        mScaleBarOverlay.setMaxLength(0.85f);

        mMapController = (MapController) mMapViewOnline.getController();//获取MapView控制器
        mMapController.setCenter(_geopoint);//设置地图中心
        mMapViewOnline.setMaxZoomLevel(20);
        mMapViewOnline.setMinZoomLevel(6);
        mMapController.setZoom(15);//设置缩放级别
        mMapViewOnline.setBuiltInZoomControls(false);//设置缩放按钮可见
        mMapViewOnline.setMultiTouchControls(true);//设置多指触控可用
        mMapViewOnline.setLayerType(View.LAYER_TYPE_SOFTWARE, null);//关闭硬件加速(绘制轨迹时需要)

    }

    //Mapsforge引擎
    public org.mapsforge.map.android.view.MapView mapView = null;
    private RotateView rotateViewMapsforge = null;
    private PreferencesFacade preferencesFacade;
    private List<TileCache> tileCaches = new ArrayList<TileCache>();

    private String getPersistableId() {
        return "OSMActivity";
//        return this.getClass().getSimpleName();
    }

    private float getScreenRatio() {
        return 1.0f;//dp:px
    }

    String _mapdir = "";
    String _mapsforgedir = "";//mapsforge的目录

    private MapDataStore getMapFile() {
//        String mapdir = Environment.getExternalStorageDirectory() + "/BHCMapper/mapsforge";
        if (SysUtils.getInstance().mapsforgeFile.exists()) {
            _mapdir = SysUtils.getInstance().mapsforgeFile.getAbsolutePath();
            _mapsforgedir = SysUtils.getInstance().mapsforgeFile.getParent();
        } else {
            return null;
        }

        return new MapFile(SysUtils.getInstance().mapsforgeFile);
    }

    private XmlRenderTheme getRenderTheme() {
        return InternalRenderTheme.DEFAULT;
    }

    private HillsRenderConfig hillsConfig = null;

    private HillsRenderConfig getHillsRenderConfig() {
        File demFolder = new File(Environment.getExternalStorageDirectory() + "/BHCMapper/", "dem");
        if (!(demFolder.exists() && demFolder.isDirectory() && demFolder.canRead() && demFolder.listFiles().length > 0)) {
            demFolder = new File("/mnt/sdcard2/BHCMapper/", "dem");
        }
        
        if (!(demFolder.exists() && demFolder.isDirectory() && demFolder.canRead() && demFolder.listFiles().length > 0)) {
            hillsConfig = null;
        } else {
            // minimum setup for hillshading
            MemoryCachingHgtReaderTileSource hillTileSource = new MemoryCachingHgtReaderTileSource(demFolder, new SimpleShadingAlgorithm(), AndroidGraphicFactory.INSTANCE);
            hillTileSource.setEnableInterpolationOverlap(false);
            hillsConfig = new HillsRenderConfig(hillTileSource);

            // call after setting/changing parameters, walks filesystem for DEM metadata
            hillsConfig.indexOnThread();
        }
        return hillsConfig;
    }

    private byte getZoomLevelMin() {
        return (byte) 0;
    }

    /**
     * @return the maximum zoom level of the map view.
     */
    private byte getZoomLevelMax() {
        return (byte) 24;
    }

    private void intMapsforge() {
        boolean isFirst = false;
        if (mapView == null) {
            mapView = (org.mapsforge.map.android.view.MapView) findViewById(R.id.id_mapViewM);
            rotateViewMapsforge = (RotateView) findViewById(R.id.rotateView);

            isFirst = true;
        }

        //createSharedPreferences
        if (!SysUtils.getInstance().mapsforgeFile.exists()) {
            mapView.setVisibility(View.GONE);
            rotateViewMapsforge.setVisibility(View.GONE);
            return;
        } else {
            mapView.setVisibility(View.VISIBLE);
            rotateViewMapsforge.setVisibility(View.VISIBLE);
        }

        if (isFirst) {
            preferencesFacade = new AndroidPreferences(getContext().getSharedPreferences(getPersistableId(), Context.MODE_PRIVATE));
            //createMapViews
            Parameters.FRAME_BUFFER_HA2 = true;
            mapView.getModel().init(preferencesFacade);//设置MapPosition
            mapView.setClickable(true);
            mapView.getMapScaleBar().setVisible(true);
            mapView.setBuiltInZoomControls(false);
            mapView.getMapScaleBar().setScaleBarPosition(MapScaleBar.ScaleBarPosition.BOTTOM_RIGHT);

            mapView.getModel().mapViewPosition.setZoomLevel((byte) 16);
            mapView.setCenter(new LatLong(39.986250, 116.400025));
        } else {
            if (_mapdir.compareToIgnoreCase(SysUtils.getInstance().mapsforgeFile.getAbsolutePath()) == 0) {
                return;
            }
        }

        //createLayers
        if (mTileRendererLayer != null) {
            mapView.getLayerManager().getLayers().remove(mTileRendererLayer);
        }

        if (tileCaches.size() < 1) {
            //createTileCaches
            mapView.getModel().mapViewPosition.setZoomLevel((byte) 16);
            tileCaches.add(AndroidUtil.createTileCache(getContext(), getPersistableId(),
                    mapView.getModel().displayModel.getTileSize(), getScreenRatio(),
                    mapView.getModel().frameBufferModel.getOverdrawFactor(), true));
        }

//        MapDataStore mapDataStore = getMapFile();
//        if (mapDataStore != null) {
//            mTileRendererLayer = AndroidUtil.createTileRendererLayer(tileCaches.get(0),
//                    mapView.getModel().mapViewPosition, mapDataStore, getRenderTheme(), false, true, false,
//                    getHillsRenderConfig());
//            mapView.getLayerManager().getLayers().add(0, mTileRendererLayer);//可以加多个图层
//        }

        multiMapDataStore = new MultiMapDataStore(MultiMapDataStore.DataPolicy.RETURN_ALL);
        if (SysUtils.getInstance().mapsforgeFile.exists()) {
            _mapdir = SysUtils.getInstance().mapsforgeFile.getAbsolutePath();
            _mapsforgedir = SysUtils.getInstance().mapsforgeFile.getParent();
            seachFile(_mapsforgedir);

            for (int i = 0; i < filenamelist.size(); i++) {
                MapFile mapFile = new MapFile(SysUtils.getInstance().mapsforgeFile);
                multiMapDataStore.addMapDataStore(mapFile, false, false);
            }
            mTileRendererLayer = AndroidUtil.createTileRendererLayer(tileCaches.get(0),
                    mapView.getModel().mapViewPosition, multiMapDataStore, getRenderTheme(), false, true, false,
                    getHillsRenderConfig());
            mapView.getLayerManager().getLayers().add(0, mTileRendererLayer);//可以加多个图层

            mapView.getModel().mapViewPosition.setZoomLevel((byte) 16);
        }

    }

    private ArrayList<String> filenamelist = new ArrayList<String>();;
    private void seachFile(String path) {
        filenamelist.clear();

        File fRoot = new File(path);
        File[] files = fRoot.listFiles();
        if (files == null)
            return;

        for (int j = 0; j < files.length; j++) {
            String fName = files[j].getName();
            if (filenamelist.contains(fName)) {
                continue;
            }
            if (files[j].isDirectory()) {
                continue;
            } else {
                if (fName.contains(".map")) {
                    filenamelist.add(fName);
                }
            }
        }
    }

    MultiMapDataStore multiMapDataStore;
    TileRendererLayer mTileRendererLayer;


    //save MapPosition
    private void save() {
        mapView.getModel().save(preferencesFacade);
        preferencesFacade.save();
    }

    public void destroyMap() {
        mapView.destroyAll();
        AndroidGraphicFactory.clearResourceMemoryCache();
        tileCaches.clear();
    }


}
